using Aspire.Hosting.Lifecycle;

namespace MoMing.VideoTool.AppHost
{
    /// <summary>
    /// 提供IDistributedApplicationBuilder扩展方法的静态内部类。
    /// </summary>
    internal static class Extensions
    {
        /// <summary>
        /// 向应用程序中的所有项目添加钩子，以设置ASPNETCORE_FORWARDEDHEADERS_ENABLED环境变量为true。
        /// 此操作启用了处理由代理或负载均衡器添加的转发头（如X-Forwarded-For和X-Forwarded-Proto）的ASP.NET Core转发头中间件。
        /// </summary>
        /// <param name="builder">IDistributedApplicationBuilder实例。</param>
        /// <returns>添加了钩子后的IDistributedApplicationBuilder实例。</returns>
        public static IDistributedApplicationBuilder AddForwardedHeaders(this IDistributedApplicationBuilder builder)
        {
            builder.Services.TryAddLifecycleHook<AddForwardHeadersHook>();
            return builder;
        }

        /// <summary>
        /// AddForwardHeadersHook类实现了IDistributedApplicationLifecycleHook接口，用作生命周期钩子。
        /// 其目的是在应用启动前启用ASP.NET Core转发头中间件。
        /// </summary>
        private class AddForwardHeadersHook : IDistributedApplicationLifecycleHook
        {
            /// <summary>
            /// 应用程序启动前执行的逻辑。
            /// 为每个项目资源添加环境变量配置以启用转发头中间件。
            /// </summary>
            /// <param name="appModel">分布式应用模型。</param>
            /// <param name="cancellationToken">取消令牌。</param>
            /// <returns>表示操作完成的任务。</returns>
            public Task BeforeStartAsync(DistributedApplicationModel appModel, CancellationToken cancellationToken = default)
            {
                // 遍历所有项目资源以添加环境变量配置
                foreach (var p in appModel.GetProjectResources())
                {
                    // 添加注解以设置ASPNETCORE_FORWARDEDHEADERS_ENABLED环境变量为true
                    p.Annotations.Add(new EnvironmentCallbackAnnotation(context =>
                    {
                        context.EnvironmentVariables["ASPNETCORE_FORWARDEDHEADERS_ENABLED"] = "true";
                    }));
                }

                // 操作完成，返回已完成任务
                return Task.CompletedTask;
            }
        }
    }
}